// pages/post-detail/post-detail.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const $ = db.command.aggregate
const dayjs = app.require("lib/day")
const to = app.require("lib/awaitTo")
const loginCheck = app.require("utils/loginCheck")

const { addMessage } = app.require("utils/request/message")
// 引入mixins
const collection = require("./mixins/collection")
const favor = require("./mixins/favor")
const comment = require("./mixins/comment")
Page({
	/**
	 * 页面的初始数据
	 */
	mixins: [collection, favor, comment],
	data: {
		user: wx.getStorageSync('user'),
		postId: "",
		post: {}
	},
	onLoad(e) {
		this.setData({
			postId: e.postId,
		})
		this.getComment()
		this.getPostDetail()
		this.addViewNum()

	},
	addViewNum() {
		// 文章浏览+1
		db.collection("post").doc(this.data.postId).update({
			data: {
				viewNum: _.inc(1)
			}
		})
	},
	async getPostDetail() {
		// 获取文章详情
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		const [err, res] = await to(db.collection("post")
			.aggregate()
			.project({
				userId: true,
				isFavor: $.in([this.data.user._id || '', '$favor']),
				isCollection: $.in([this.data.user._id || '', '$collection']),
				favorNum: true,
				collectionNum: true,
				user: {
					nickName: true,
					avatarUrl: true
				},
				title: true,
				content: true,
				imgList: true,
				viewNum: true,
				createTime: true
			})
			.end(), "getPostDetail")
		wx.hideLoading()
		if (err) return
		if (res.list.length) {
			const post = res.list[0]
			post.createTime = dayjs().from(post.createTime)
			this.setData({
				post
			})
			// 设置页面标题为文章标题
			wx.setNavigationBarTitle({
				title: post.title.length >= 15 ? `${post.title.substr(0, 15)}...` : post.title
			})
		} else {
			wx.showToast({
				title: '文章已删除',
				icon: "none"
			})
		}
	},
	showUserPage() {
		// 跳转用户主页
		const {
			showUserPage
		} = app.require("utils/router/user")
		showUserPage(this.data.post.userId)
	},
	previewImage(e) {
		// 预览图片
		wx.previewImage({
			urls: this.data.post.imgList,
			current: e.currentTarget.dataset.index
		})
	},
	async handleTabbar(e) {
		// 底部栏操作
		if (await loginCheck()) { return }
		const handleArr = ['collection', 'favor', 'showComment']
		this[handleArr[e.detail]]()
	},
	addMessage({ type, content = "" }) {
		addMessage({ type, post: this.data.post, _receiverId: this.data.post.userId, content })
	},
	onShareAppMessage() {
		return {
			title: this.data.post.title,
			path: `/pages/post-detail/post-detail?postId=${this.data.postId}`,
		}
	},
	onShareTimeline() {
		return {
			title: this.data.post.title,
			path: `/pages/post-detail/post-detail?postId=${this.data.postId}`,
		}
	},
})